package com.cw.demo.thread;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * TODO
 *
 * @author chenw
 * @date 2021/10/11
 */
public class ProducerTest {
    static int queueSize = 10;
    ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(queueSize);

    public static void main(String[] args) {
        ProducerTest producerTest = new ProducerTest();
        Producer producer = producerTest.new Producer();
        Consumer consumer = producerTest.new Consumer();
        Thread t = new Thread(producer);
        Thread tt = new Thread(consumer);
        t.start();
        tt.start();


    }
    class Producer implements Runnable {
        @Override
        public void run() {
            try {
                produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void produce() throws InterruptedException {
            while (true) {
                arrayBlockingQueue.put(1);
                System.out.println("存取一个产品,队列剩余空间：" + arrayBlockingQueue.size());
            }
        }
    }

    class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void consumer() throws InterruptedException {
            while (true) {
                arrayBlockingQueue.take();
                System.out.println("消费一个产品,队列剩余空间：" + arrayBlockingQueue.size());
            }
        }
    }
}
